import React from 'react';
import { inject, observer } from 'mobx-react';
import { Condition, getAdButtons } from '../list/listCondition';
import { WeaTableNew } from 'comsMobx';
import { WeaRightMenu, WeaTop, WeaTab, WeaErrorPage, WeaTools, WeaProgress, WeaLocaleProvider } from 'ecCom';
const WeaTable = WeaTableNew.WeaTable;
const getLabel = WeaLocaleProvider.getLabel;
import ShareDialog from '../dialog/shareDialog'
import ExchangeDialog from '../dialog/exchangeDialog'
import TaskInfoDialog from '../dialog/taskDialog'

@inject('taskExecuteStore')
@observer
class TaskExecute extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            workPlanVisible: false,
            coWorkVisiable : false,
            taskid: "",
            projectid: ""
        }
    }

    componentDidMount() {
        const { taskExecuteStore } = this.props;
        this.doInit(this.props);
        // if (!window.weaWorkplan) {
        //     // 异步加载别模块的静态资源
        //     eventRegister.loadModule('f_workplan', () => {
        //         taskExecuteStore.setLoaded(true)
        //     }, () => {
        //         // 加载文件失败 的业务处理， 网络超时，没文件之类
        //     })
        // } else {
        //     taskExecuteStore.setLoaded(true)
        // }

        if (!window.weaWorkplan && !window.weaCowork) {
            eventRegister.loadModule('f_workplan', () => {
                eventRegister.loadModule('f_cowork', () => {
                    taskExecuteStore.setLoaded(true)
                }, () => {
                    // 加载文件失败 的业务处理， 网络超时，没文件之类
                    alert("加载协作模块失败，请联系系统管理员！");
                });
            }, () => {
                // 加载文件失败 的业务处理， 网络超时，没文件之类
                alert("加载日程模块失败，请联系系统管理员！");
            });
            return;
        }
        if (window.weaWorkplan && !window.weaCowork) {
            eventRegister.loadModule('f_cowork', () => {
                taskExecuteStore.setLoaded(true)
            }, () => {
                // 加载文件失败 的业务处理， 网络超时，没文件之类
                alert("加载协作模块失败，请联系系统管理员！");
            });
        } else {
            eventRegister.loadModule('f_workplan', () => {
                taskExecuteStore.setLoaded(true)
            }, () => {
                // 加载文件失败 的业务处理， 网络超时，没文件之类
                alert("加载协作模块失败，请联系系统管理员！");
            });
        }
    }
    doInit(props) {
        const { location, taskExecuteStore } = props;
        const { initDatas, doSearch } = taskExecuteStore;
        initDatas();
        doSearch();
    }
    componentWillReceiveProps(nextProps) {
        const keyOld = this.props.location.key;
        const keyNew = nextProps.location.key;
        if (keyOld !== keyNew) {
            const { taskExecuteStore, location } = nextProps;
            const { initDatas, doSearch } = taskExecuteStore;
            taskExecuteStore.clearStatus();
            initDatas();
            doSearch();
        }
    }
    componentWillUnmount() {
        const { taskExecuteStore } = this.props;
        taskExecuteStore.clearStatus();
    }
    render() {
        const { taskExecuteStore } = this.props;
        let title = getLabel(33103, "任务执行");
        let topTab = [
            {
                color: '#000000',
                groupid: 'totalCount1',
                showcount: true,
                title: getLabel(332, "全部"),
                tabkey: "all"
            },
            {
                color: '#ff3232',
                groupid: 'totalCount2',
                showcount: true,
                title: getLabel(1979, "未开始"),
                tabkey: "todo"
            },
            {
                color: '#fea468',
                groupid: 'totalCount3',
                showcount: true,
                title: getLabel(1960, "进行中"),
                tabkey: "doing"
            },
            {
                color: '#9766fd',
                groupid: 'totalCount4',
                showcount: true,
                title: getLabel('21984', "已超期"),
                tabkey: "overtime"
            }
        ];
        const { loading, tableStore, showSearchAd, showBatchSubmit, form, config, topTabCount, searchParams, exchangeStore, taskInfoStore, reLoad } = taskExecuteStore;
        const formParams = form.getFormParams() || {};
        const account = WeaTools.ls.getJSONObj('theme-account');
        let _this = this;
        return (
            <WeaRightMenu ecId={`${this && this.props && this.props.ecId || ''}_WeaRightMenu@kf9k2a`} datas={this.getRightMenu()} onClick={this.onRightMenuClick.bind(this)} >
                <WeaTop ecId={`${this && this.props && this.props.ecId || ''}_WeaTop@nslxi8`}
                    title={title}
                    loading={loading}
                    icon={<i className='icon-coms-project' />}
                    iconBgcolor='#217346'
                    buttons={[]}
                    buttonSpace={10}
                    showDropIcon={true}
                    dropMenuDatas={this.getRightMenu()}
                    onDropMenuClick={this.onRightMenuClick}
                >
                    <WeaTab ecId={`${this && this.props && this.props.ecId || ''}_WeaTab@vwhfxc`}
                        datas={topTab}
                        counts={topTabCount}
                        keyParam="tabkey"  //主键
                        countParam="groupid" //数量
                        selectedKey={searchParams.tabkey}
                        buttonsAd={getAdButtons(taskExecuteStore,this.props.ecId || '')}
                        searchType={['base', 'advanced']}
                        searchsBaseValue={formParams.taskname}
                        setShowSearchAd={bool => { taskExecuteStore.setShowSearchAd(bool) }}
                        hideSearchAd={() => taskExecuteStore.setShowSearchAd(false)}
                        searchsAd={
                            <div><Condition ecId={`${this && this.props && this.props.ecId || ''}_Condition@qbv5ti`} listStore={taskExecuteStore} form={form} onEnterSearch={this.onEnterSearch} ></Condition></div>
                        }
                        showSearchAd={showSearchAd}
                        onSearch={v => { taskExecuteStore.doSearch() }}
                        onSearchChange={v => { taskExecuteStore.setFormFields({ taskname: { value: v } }) }}
                        onChange={this.changeData}
                    />

                    <WeaTable ecId={`${this && this.props && this.props.ecId || ''}_WeaTable@cxe369`}
                        comsWeaTableStore={tableStore}
                        hasOrder={true}
                        needScroll={true}
                        register_table={() => reLoad()}
                        getColumns={c => this.reRenderColumns(c)}
                        tableWidth={this.tableWidth}
                        onOperatesClick={this.onOperatesClick.bind(this)}
                    />
                </WeaTop>
                {window.weaCowork && window.weaCowork.com && window.weaCowork.com.CreateCowork && this.state.coWorkVisiable && this.state.taskid !== "" && (
                    <window.weaCowork.com.CreateCowork ecId={`${this && this.props && this.props.ecId || ''}_CreateCowork@v7dy4v`}
                        initAddQuery={
                            {
                                relatedType: "task",
                                ids: this.state.taskid
                            }
                        }
                        onCancel={() => {
                            this.setState({
                                coWorkVisiable: false
                            });
                        }}
                    />)
                }
                {
                    taskExecuteStore.isreloadWorkPlan && window.weaWorkplan && window.weaWorkplan.com && window.weaWorkplan.com.WorkPlanCreate &&
                    (<window.weaWorkplan.com.WorkPlanCreate ecId={`${this && this.props && this.props.ecId || ''}_WorkPlanCreate@49f3jg`}
                        type={"create"}//新建为'create',查看为'preview',编辑edit,共享share
                        visible={_this.state.workPlanVisible}//显隐受控
                        doClose={() => { _this.setWorkPlanVisible(false); }}//关闭回调
                        onlyClose={() => { _this.setWorkPlanVisible(false) }}//关闭回调,只做关闭操作
                        workPlanId={""} //日程id，1查看日程时用到
                        createConditionParams={[]}//创建的默认值日期和时间,没有传[]
                        activeKey={""} //查看页面显示的面板1是基本信息，7是相关交流
                        //changeTab={(key) => { }}//查看页面切换面板的回调
                        selectUser={account && account.userid}//新建日程的创建人id
                        workPlanTypeOptions={"2"}//客户模块的新建日程，普通新建传'',客户新建传3
                        projectid={_this.state.projectid}
                        taskid={_this.state.taskid}
                        description={""}//客户模块需求，支持新建时传入的'基本信息-内容'
                    />)
                }
                <ShareDialog ecId={`${this && this.props && this.props.ecId || ''}_ShareDialog@3a30fv`} contentStore={taskExecuteStore} />
                <ExchangeDialog ecId={`${this && this.props && this.props.ecId || ''}_ExchangeDialog@vawj7i`} contentStore={exchangeStore} />
                <TaskInfoDialog ecId={`${this && this.props && this.props.ecId || ''}_TaskInfoDialog@qy2qn3`} contentStore={taskInfoStore} />
            </WeaRightMenu>)

    }

    onEnterSearch=() =>{
        const { taskExecuteStore } = this.props;
        taskExecuteStore.doSearch();
        taskExecuteStore.setShowSearchAd(false);
    }

    setWorkPlanVisible = (bool) => {
        this.setState({ workPlanVisible: bool })
    }

    getRightMenu() {
        const { taskExecuteStore } = this.props;
        const { rightMenu } = taskExecuteStore;
        let btnArr = [];
        rightMenu && rightMenu.length > 0 && rightMenu.map(m => {
            btnArr.push({
                icon: <i className={m.menuIcon} />,
                content: m.menuName
            })
        });
        return btnArr
    }
    onRightMenuClick = (key)=>{
        const { taskExecuteStore } = this.props;
        const { rightMenu } = taskExecuteStore;
        let that = this;
        rightMenu && rightMenu.length > 0 && rightMenu.map((m, i) => {
            if (Number(key) == i) {
                let fn = m.menuFun.indexOf('this') >= 0 ? `${m.menuFun.split('this')[0]})` : m.menuFun;
                if (m.type == "BTN_COLUMN") { //定制列
                    taskExecuteStore.onShowColumn();
                }
            }
        });
    }
    reRenderColumns(columns) {
        columns.forEach((c,i) => {
            if (c.dataIndex == 'finish') {
                c.render = function (text, record) {
                    return <span className='wea-prj-progressStyle' >
                        <WeaProgress ecId={`${this && this.props && this.props.ecId || ''}_WeaProgress@2rz8ed@${i}`} percent={record.finish || 0} strokeColor={record.finishspan} />
                    </span>
                }
            } else {
                c.render = function (text, record) {
                    let valueSpan = record[c.dataIndex + "span"] !== undefined ? record[c.dataIndex + "span"] : record[c.dataIndex];
                    return <span dangerouslySetInnerHTML={{ __html: valueSpan }}></span>
                }
            }
        })
        return columns;
    }

    tableWidth = (columns) => {
        let width = 0;
        let cols = 0;
        columns.map(col => {
          if (col.display === 'true') {
            let oldwidth = col.oldWidth || '10%';
            let widthInt = parseFloat(oldwidth.replace('%', ''));
            if (widthInt <= 0) {
              widthInt = 10;
            }
            width += widthInt;
            cols++
          }
        })
        //超过10列，才出现滚动条，width>100才出现滚动条
        if(cols<=10){
            width = 100 ;
        }
        return `${width}%`;
    }

    changeData = (key) => {
        const { taskExecuteStore } = this.props;
        taskExecuteStore.setShowSearchAd(false);
        taskExecuteStore.doSearch({
            tabkey: key
        });
    }
    onOperatesClick(record, index, operate, flag) {
        const { taskExecuteStore: { shareStore, exchangeStore, taskInfoStore } } = this.props;
        let _href = operate && operate.href ? operate.href : "";
        let fn = _href.replace("javascript:", "");
        fn = fn.substring(0, fn.indexOf('('));
        let that = this;
        if (fn != "") {
            if ("onShare" == fn) {  //共享
                shareStore.handleShareDialog(true, "task", record.randomFieldId, {})
            } else if ('onNewCowork' == fn) {   //新建协作
                this.setState({ coWorkVisiable: true, taskid: record.randomFieldId, projectid: record.prjid })
                const coworkStoreMap = window.weaCowork.store && window.weaCowork.store.coworkStoreMap;
                const cowortore = coworkStoreMap && coworkStoreMap.getMapStore(3);
                cowortore && cowortore.setCreateState({ showNewCowork: true, createOrEdit: 0 });
            } else if ('onNewWorkplan' == fn) {   //新建日程
                this.setState({ workPlanVisible: true, taskid: record.randomFieldId, projectid: record.prjid })
            } else if ('onApprove' == fn) {   //

            } else if ('onReject' == fn) {   //

            } else if ('onEdit' == fn) {   //编辑
                taskInfoStore.handleDialog(true, "edit", record.randomFieldId);
            } else if ('onDiscuss' == fn) {   //相关交流
                exchangeStore.handleExchangeDialog(true, "task", record.randomFieldId, {})
            } else if ('onDel' == fn) {   //删除
                taskInfoStore.delTask("del", record.randomFieldId);
            }
        }
    }
}

export default WeaTools.tryCatch(React,
    props => <WeaErrorPage ecId={`${this && this.props && this.props.ecId || ''}_WeaErrorPage@w09md4`} msg={props.error ? props.error : getLabel(383324, "对不起，该页面异常，请联系管理员")} />,
    { error: "" }
)(TaskExecute);